<template>
  <div class="questionSet-container">
    <div class="page-header">
      <div class="page-title">
        <h1>题目集管理</h1>
        <p class="text-muted">创建和管理不同职位的面试题目集</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>添加题目集
        </el-button>
      </div>
    </div>

    <!-- 筛选器区域 -->
    <el-card class="filter-card">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="职位">
            <el-select
                v-model="filterForm.positionId"
                placeholder="所有职位"
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in positionOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职位级别">
            <el-select
                v-model="filterForm.level"
                placeholder="所有级别"
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="filterForm.status"
                placeholder="所有状态"
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 题目集列表 -->
    <el-card v-loading="loading">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="题目集名称" align="center" />
        <el-table-column label="职位" align="center">
          <template #default="{ row }">
            {{ row.positionName }}
          </template>
        </el-table-column>
        <el-table-column label="题目数量" width="100" align="center">
          <template #default="{ row }">
            {{ row.questionCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="职位级别" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(getPositionLevel(row.positionsId || row.positionId))">
              {{ getPositionLevel(row.positionsId || row.positionId) || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'warning'">
              {{ row.status === 0 ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-link type="primary" :underline="'never'" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
              </el-link>
              <el-link type="danger" :underline="'never'" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑题目集对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加题目集' : '编辑题目集'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="题目集名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入题目集名称" />
        </el-form-item>
        <el-form-item label="题目集描述" prop="description">
          <el-input
              v-model="form.description"
              :rows="3"
              placeholder="请输入题目集描述"
              type="textarea"
          />
        </el-form-item>
        <el-form-item label="职位" prop="positionsId">
          <el-select v-model="form.positionsId" placeholder="请选择职位" style="width: 100%">
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'
import {
  addQuestionSet,
  deleteQuestionSet,
  updateQuestionSet,
  pageByPosition,
  pageByPositionLevel,
  pageByStatus
} from '@/api/questionSet'
import { queryPositions } from '@/api/questionSet'
import { getPositionList } from '@/api/position'

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  positionId: '',  // 职位ID，默认为空表示所有职位
  level: '',       // 级别
  status: undefined  // 状态，默认为undefined表示所有状态
})

// 职位选项
const positionOptions = ref([])

// 职位级别选项
const levelOptions = [
  { label: '初级', value: '初级' },
  { label: '中级', value: '中级' },
  { label: '高级', value: '高级' },
  { label: '资深', value: '资深' },
  { label: '专家', value: '专家' }
]

// 状态选项
const statusOptions = [
  { label: '已启用', value: 0 },
  { label: '已禁用', value: 1 }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  positionsId: null,
  status: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入题目集名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  positionsId: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 日期格式化函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 添加加载状态
const loading = ref(false)

// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 添加重试函数
const retry = async (fn, retries = 3, delay = 1000) => {
  try {
    return await fn()
  } catch (error) {
    if (retries === 0) throw error
    await new Promise(resolve => setTimeout(resolve, delay))
    return retry(fn, retries - 1, delay)
  }
}

// 获取职位列表
const fetchPositions = async () => {
  try {
    const res = await request({
      url: '/api/positions/query',
      method: 'post',
      data: {
        pageNum: 1,
        pageSize: 100
      },
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (res.code === 200) {
      // 修改职位数据的映射
      const positions = res.data.records.map(item => ({
        id: item.id,
        name: item.positionName,
        level: item.positionLevel,
        status: item.status
      }))

      positionOptions.value = positions
      console.log('职位列表数据:', positions)  // 添加日志
    } else {
      ElMessage.error(res.message || '获取职位列表失败')
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    ElMessage.error('获取职位列表失败，请稍后重试')
  }
}

// 获取题目集列表
const fetchQuestionSets = async () => {
  loading.value = true
  try {
    // 构建基础查询参数
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 只有当有值时才添加筛选条件
    if (filterForm.positionId) {
      queryParams.positionsId = filterForm.positionId
    }
    if (filterForm.level) {
      queryParams.level = filterForm.level
    }
    if (filterForm.status !== undefined && filterForm.status !== '') {
      queryParams.status = filterForm.status
    }

    console.log('查询参数:', queryParams)

    const res = await request({
        url: '/api/questionSet/page/condition',
        method: 'post',
        data: queryParams,
        headers: {
          'Content-Type': 'application/json'
        },
      timeout: 30000
    })
    
    if (res && res.code === 200) {
      const records = res.data.records || []
      console.log('获取到的题目集数据:', records)
      
      // 获取每个题目集的题目数量
      const questionCounts = await Promise.all(
        records.map(async (item) => {
          try {
            const countResponse = await request({
              url: `/api/question/count/byProblemsetId/${item.id}`,
              method: 'get',
              timeout: 10000
            })
            return countResponse.code === 200 ? countResponse.data : 0
          } catch (error) {
            console.error('获取题目数量失败:', error)
            return 0
          }
        })
      )
      
      // 处理返回的数据，提前处理职位名称
      tableData.value = records.map((item, index) => {
        const positionId = item.positionsId || item.positionId
        const position = positionOptions.value.find(p => p.id === positionId)
        
        return {
        ...item,
        questionCount: questionCounts[index] || 0,
          positionsId: positionId,
          positionName: position ? position.name : '-',
          positionLevel: position ? position.level : '-',
        status: item.status || 0
        }
      })
      
      total.value = res.data.total || 0
      
      if (tableData.value.length === 0) {
        ElMessage.info('暂无数据')
      }
    } else {
      throw new Error(res?.message || '获取题目集列表失败')
    }
  } catch (error) {
    console.error('获取题目集列表失败:', error)
    ElMessage.error(error.message || '获取题目集列表失败，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(form, {
    id: null,
    name: '',
    positionsId: null,
    status: 0
  })
}

// 编辑题目集
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    positionsId: row.positionsId,
    status: row.status
  })
}

// 删除题目集
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目集吗？', '提示', {
      type: 'warning'
    })
    await deleteQuestionSet(row.id)
    ElMessage.success('删除成功')
    fetchQuestionSets()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除题目集失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          id: form.id,
          name: form.name,
          positionsId: form.positionsId,
          status: form.status
        }
        
        console.log('提交的数据:', submitData)
        
        if (dialogType.value === 'add') {
          const response = await request({
            url: '/api/questionSet',
            method: 'post',
            data: submitData,
            headers: {
              'Content-Type': 'application/json'
            },
            timeout: 15000
          })
          
          console.log('添加响应:', response)
          
          if (response && response.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            fetchQuestionSets()
          } else {
            throw new Error(response?.message || '添加失败')
          }
        } else {
          const response = await request({
            url: '/api/questionSet',
            method: 'put',
            data: submitData,
            headers: {
              'Content-Type': 'application/json'
            },
            timeout: 15000
          })
          
          console.log('更新响应:', response)
          
          if (response && response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchQuestionSets()
          } else {
            throw new Error(response?.message || '更新失败')
          }
        }
      } catch (error) {
        console.error('保存题目集失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response,
          request: error.request
        })
        ElMessage.error(error.message || '保存失败，请稍后重试')
      }
    }
  })
}

// 使用防抖处理筛选
const handleFilter = debounce(() => {
  currentPage.value = 1
  fetchQuestionSets()
}, 300)

// 使用防抖处理重置
const resetFilter = debounce(() => {
  filterForm.positionId = ''  // 清空职位选择
  filterForm.level = ''       // 清空级别选择
  filterForm.status = undefined  // 重置为所有状态
  currentPage.value = 1
  fetchQuestionSets()
}, 300)

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchQuestionSets()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchQuestionSets()
}

// 添加计算属性来缓存职位名称
const positionNameMap = ref(new Map())

// 修改获取职位名称的方法
const getPositionName = (positionId) => {
  if (!positionId) return '-'
  
  // 如果已经缓存过，直接返回
  if (positionNameMap.value.has(positionId)) {
    return positionNameMap.value.get(positionId)
  }
  
  const position = positionOptions.value.find(p => p.id === positionId)
  const name = position ? position.name : '-'
  
  // 缓存结果
  positionNameMap.value.set(positionId, name)
  return name
}

// 在职位列表更新时清空缓存
watch(positionOptions, () => {
  positionNameMap.value.clear()
}, { deep: true })

// 获取职位级别
const getPositionLevel = (positionId) => {
  if (!positionId) return '-'
  const position = positionOptions.value.find(p => p.id === positionId)
  return position ? position.level : '-'
}

// 获取难度标签类型
const getLevelTagType = (level) => {
  if (!level || level === '-') return 'info'
  const types = {
    '初级': 'info',
    '中级': 'primary',
    '高级': 'warning',
    '资深': 'success',
    '专家': 'danger'
  }
  return types[level] || 'info'
}

// 职位列表
const positionList = ref([])

// 获取职位列表
const getPositions = async () => {
  try {
    const res = await getPositionList()
    if (res?.data) {
      positionList.value = res.data
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    ElMessage.error('获取职位列表失败')
  }
}

// 初始化
onMounted(async () => {
  try {
    await fetchPositions()
    await fetchQuestionSets()
    await getPositions()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.questionSet-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title h1 {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 8px;
}

.text-muted {
  color: var(--el-text-color-secondary);
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 0;
  margin-bottom: 0;
}

:deep(.el-select) {
  width: 200px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.operation-buttons .el-link {
  display: flex;
  align-items: center;
  gap: 4px;
}

.operation-buttons .el-icon {
  font-size: 16px;
}
</style> 